package hanxx.security.filter;

import hanxx.common.utils.*;
import hanxx.security.domain.SysUserLogin;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String uuid;
        try {
            Claims claims = JwtUtils.parseJWT(token);
            uuid = claims.get("login_user_uuid",String.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        try {
            String redisKey = "login_user_uuid:" + uuid;
            //todo 添加上，刷新登录时间
            SysUserLogin userLogin = redisCache.getCacheObject(redisKey);
            /*if(Objects.isNull(userLogin)){
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.FORBIDDEN, "用户未登录或已经失效，请重新登录！")));
//                filterChain.doFilter(request, response);
                return;
            }*/
            redisCache.expire(redisKey,30, TimeUnit.MINUTES);
            //存入SecurityContextHolder
            // 获取权限信息封装到Authentication中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userLogin,null,userLogin.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            /*Menu menu = new Menu();
            menu.setMenuId(555555l);
            menu.setCreateTime(DateUtils.getNowDate());
            BaseEntityCache.set("Menu",menu);

            SysUser sysUser = new SysUser();
            sysUser.setPassword("wr34534533");
            sysUser.setUserName("韩鑫鑫");
            BaseEntityCache.set("SysUser",sysUser);*/

        } catch (Exception e){
            throw new RuntimeException("未知错误");
        }
        //放行
        filterChain.doFilter(request, response);
    }
}
